package com.kakame.tibbers.front.controller.friend;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.kakame.tibbers.common.constants.Tibbers;
import com.kakame.tibbers.common.models.AuthMenu;
import com.kakame.tibbers.common.models.AuthUser;
import com.kakame.tibbers.common.models.FriendGroup;
import com.kakame.tibbers.service.auth.FriendService;

public class FriendController extends Controller {
	
	private FriendService friendService = Duang.duang(FriendService.class);
	
	public void view() {
		Object sessionAttr = getSessionAttr(Tibbers.SESSION_USER);
		AuthUser user = (AuthUser)sessionAttr;
		
		List<FriendGroup> friends = friendService.listGroupByUserId(user.getId());
		
		List<AuthMenu> groups = new ArrayList<AuthMenu>();
		for (FriendGroup friendGroup : friends) {
			Integer menuId = friendGroup.getId();
			
			boolean existFlag = false;
			for (AuthMenu authMenu : groups) {
				if(menuId == authMenu.getId()) {
					existFlag = true;
					break;
				}
			}
			if(!existFlag) {
				AuthMenu menu = new AuthMenu();
				menu.setMenuName(friendGroup.getGroupName());
				menu.setMenuUrl("" + friendGroup.getFriendId());
				menu.setMenuCode("" + friendGroup.getFriendId());
				menu.setId(menuId);
				groups.add(menu);
			}
		}
		
		for (AuthMenu authMenu : groups) {
			List<AuthMenu> childs = new ArrayList<AuthMenu>();
			for (FriendGroup friendGroup : friends) {
				if(friendGroup.getId() == authMenu.getId()) {
					AuthMenu menu = new AuthMenu();
					menu.setMenuName(friendGroup.getGroupName());
					menu.setMenuUrl("" + friendGroup.getFriendId());
					menu.setMenuCode("" + friendGroup.getFriendId());
					menu.setId(friendGroup.getFriendId());
					menu.setPid(friendGroup.getId());
					childs.add(menu);
				}
			}
			authMenu.setChildList(childs);
		}
		
		setAttr("menuList", groups);
		
		renderTemplate("view.html");
	}
	
}
